<?php
/**
 * Student Report Controller
 *
 * Student  Information Report
 * student entry
 *
 * @version $Id: ReportController.php 126 2010-06-27 04:01:38Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Zend_Controller_Action
 * @package student
 * @subpackage Controller
 */

//TODO 國中報表及自訂報表
class Student_ReportController extends Zend_Controller_Action
{
    private $_reports; // 報表種類
    private $_store_path; // 自訂報表儲存位置
    private $_arrayData;  // 學籍相關設定資料
    private $_roundNum; // 小數位數
    private $_finScoreRateMode ; //學期平均計算方式
    private $_displayFinScoreRate; // 是否顯示學分平均


    public function init()
    {

        //print_r($this->view->School) ;exit;
        $this-> _store_path = $this->_helper->getStorePath('student/report'); // 取得存放路徑
        $this->_reports = array(
            'reg_ps' => $this->view->translate('Elementary School report'),
            'reg_jh' => $this->view->translate('Junior high school report')
        );
        $locale = Bootstrap::$config['resources']['locale']['default'];
        $path = dirname(__FILE__)."/../languages/$locale/data.ini";
        $ini = new Zend_Config_Ini($path);
        $this->_arrayData = $ini->get('array_data')->toArray();

        // 取系統預設值
        $param = new Default_Model_ModulesParam();
        $param_arr = $param->getParamByResourceId('score');
        // 小數計算位數
        $this->_roundNum = $param_arr['round_number'] ;
        $this->_finScoreRateMode  =  $param_arr['fin_score_rate_mode'];  //學期平均計算方式
        $this->_displayFinScoreRate = $param_arr['display_fin_score_rate'];  //顯示學期平均計算方式
    }

    public function testAction()
    {

    }

    public function indexAction()
    {


        if ($this->getRequest()->getParam('act')) {
            $this->_sendReports();
        }

        if ($yearSemester  = $this->getRequest()->getPost('year_semester')) {
            $yearArr = explode("-", $yearSemester);
            $year = (int) $yearArr[0];
            $semester = (int) $yearArr[1];
            $this->view->year_semester = $this->_getParam('year_semester');
        }
        else
        $this->view->year_semester = $this->view->Semester['yearSeme'];


        if ($classGrade  = $this->getRequest()->getPost('class_grade')) {
            $classArr = explode("-", $classGrade);
            $grade = (int) $classArr[0];
            $classSn = (int) $classArr[1];

            $student  = new Student_Model_Student();
            $this->view->data = $student->getClassStudent($year,$semester,$grade,$classSn);
            $this->view->class_grade = $this->_getParam('class_grade');
        }
        $this->view->reports = $this->_reports ;

    }

    /**
     *  列印報表
     */
    protected  function _sendReports()
    {
        // 選擇學年學期 年級班級
        $tempArr  = explode('-',$this->_getParam('year_semester'));
        $selYear = (int) $tempArr[0];
        $selSemester =  (int) $tempArr[1];
        $tempArr = explode('-', $this->_getParam('class_grade'));
        $selGrade = (int) $tempArr[0];
        $selClassSn = (int) $tempArr[1];
        $presenceArr = array();
        // 上課日數
        $res = Doctrine_Query::create()
        ->from('Semester_Model_SemesterCourseDays a')
        ->Where('year >= ?', $selYear-$selGrade+1)
        ->orderBy('year, grade')
        ->fetchArray();

        // 科目標籤
        $subjectTagArray = array(
        'chinese' =>'語文-本國語文',
        'local' => '語文-鄉土語文',
        'english'=> '語文-英語',
        'health'=>'健康與體育',
        'math'=>'數學',
        'life'=>'生活',
        'social'=>'社會',
        'nature'=>'自然與生活科技',
        'art'=>'藝術與人文',
        'complex'=>'綜合活動');

        // 先取代為空值
        foreach ($subjectTagArray as $id=>$val) {
            $arr[$id.'_avg_score'] = '';
            $arr[$id.'_avg_grade'] = '';
        }


        foreach ($res as $row)
        $presenceArr[$row['year']][$row['semester']][$row['grade']] = $row['days'];


        //echo $currentYear;
        $scoreSemester  = new Student_Model_StudentScoreSemester();

        $system_text = new Default_Model_SystemText();
        $stud_kind_arr = $system_text->getKindArray('stud_kind');

        $ooPath =  dirname(__FILE__) .'/../data/report/reg_ps';
        $ooo = new Sfs_Filesystem_Ooo($ooPath);

        $content = $ooo->getContent('content.xml');
        $content = str_replace("<office:automatic-styles>",
        '<office:automatic-styles><style:style style:name="BREAKPAGE" style:family="paragraph" style:parent-style-name="Standard"><style:paragraph-properties fo:break-before="page"/></style:style>',
        $content);

        $break = '<office:text text:use-soft-page-breaks="true"><text:p text:style-name="BREAKPAGE" /></office:text>';
        $conHeadXml = '<office:body>';
        $conFootXml = '</office:body>';
        $arr1 = explode($conHeadXml,$content);

        $doc_head = $arr1[0].$conHeadXml;
        $arr2 = explode($conFootXml,$arr1[1]);
        $contentBody = $arr2[0];
        $docFoot = $conFootXml.$arr2[1];
        // manifest.xml
        $manifestStr = '';
        // 相片檔名
        $zq = new Zend_Dom_Query($content);
        $res = $zq->queryXpath("//draw:frame[@draw:name='photo']/draw:image");

        if ($res) {
            $photoTag = $res->current()->getAttribute('xlink:href');
            $splitStr = '<manifest:file-entry manifest:media-type="image/jpeg" manifest:full-path="'.$photoTag.'"/>';

            $ooo->setSkipFile('META-INF/manifest.xml');
        }

        //TODO 轉學生無學期記錄問題
        $replaceData = '';
        $studentArr = $this->_getParam('student_id') ;
        $res = Doctrine_Query::create()
        ->from('Student_Model_Student a')
        ->leftJoin('a.Student_Model_StudentSemester b')
        ->leftJoin('a.Student_Model_StudentGuardian c')
        ->leftJoin('a.Student_Model_StudentTransfer d')
        ->whereIn('sn',$studentArr)
        ->orderBy('b.number, d.date DESC')
        ->fetchArray();
        $page = 1;
        // 迴圈開始
        foreach ($res as $row) {
            $currentContentBody =  $contentBody;
            $arr = array();
            $arr['school_long_name']  = $this->view->School['name'];
            $arr['stud_name'] = $row['name'];
            $arr['stud_sex'] = $this->_arrayData['sex'][$row['sex']] ;
            $arr['enroll_school'] = $row['enroll_school'];
            $arr['stud_id'] = $row['student_id'];
            $arr['stud_birthday'] = $row['birthday'] ;
            $arr['stud_person_id'] = $row['identification_number'];
            $arr['enroll_date'] = $row['enroll_year'].'-8';
            $arr['guardian_name'] = $row['Student_Model_StudentGuardian']['name'];
            if (isset($this->_arrayData['relation'][$row['Student_Model_StudentGuardian']['relation']]))
            $arr['guardian_relation'] =
            $this->_arrayData['relation'][$row['Student_Model_StudentGuardian']['relation']];
            else
            $arr['guardian_relation'] = '';

            // TODO 再確定？ 學生身分別太多 記錄學生班別
            if ($row['class_property'] == 0 )
            $arr['stud_kind'] = $stud_kind_arr[0];
            else
            $arr['stud_kind'] = $this->_arrayData['class_property'][$row['class_property']];

            $arr['stud_addr_1'] = $row['registered_address'];
            $arr['stud_tel_1'] = $row['phone_registered'];

            // 異動記錄
            for($i=$this->view->lowYear; $i<= $this->view->highYear; $i++) {
                $arr['move_date_'.$i] = '';
                $arr['move_kind_'.$i] = '';
                $arr['move_unit_'.$i] = '';
                $arr['move_c_date_'.$i] = '';
                $arr['move_c_num_'.$i] = '';
                $arr['move_county_'.$i] = '';
                $arr['move_school_'.$i] = '';

                if (isset( $row['Student_Model_StudentTransfer'][$i-1])) {
                    $transferData = $row['Student_Model_StudentTransfer'][$i-1];
                    $arr['move_date_'.$i] = $transferData['date'];
                    $arr['move_kind_'.$i] =
                    $this->_arrayData['transfer']['kind'][$transferData['causation_kind']];
                    $arr['move_unit_'.$i] = $transferData['approve_organ'];
                    $arr['move_c_date_'.$i] = $transferData['approve_date'];
                    $arr['move_c_num_'.$i] = $transferData['approve_word'];
                    $arr['move_county_'.$i] = $transferData['county'];
                    $arr['move_school_'.$i] = $transferData['school_name'];
                }
            }
            // 先取代為空值
            $arr['avg_score'] = '';
            $arr['avg_grade'] = '';
            $arr['days_sum'] = 0;
            $arr['abs_1_sum'] = 0;
            $arr['abs_2_sum'] = 0;
            $arr['abs_3_sum'] = 0;
            $arr['abs_4_sum'] = 0;
            $arr['abs_5_sum'] = 0;
            $arr['abs_6_sum'] = 0;
            $arr['abs_total_sum'] = 0;

            // 小一 小二 科目先替換
            $arr['english_avg_score'] = '';
            $arr['english_avg_grade'] = '';
            $arr['social_avg_score'] = '';
            $arr['social_avg_grade'] = '';
            $arr['nature_avg_score'] = '';
            $arr['nature_avg_grade'] = '';
            $arr['art_avg_score'] = '';
            $arr['art_avg_grade'] = '';



            for($i=$this->view->lowYear; $i<= $this->view->highYear; $i++) {
                $arr['grade_'.$i.'_1'] = $arr['grade_'.$i.'_2'] = '';
                $arr[$i.'_1_score'] = $arr[$i.'_2_score'] = '';
                $arr[$i.'_1_grade'] = $arr[$i.'_2_grade'] = '';
                $arr['teacher_'.$i.'_1'] = $arr['teacher_'.$i.'_2'] = '';

                foreach ($subjectTagArray as $subjectTag=>$val) {
                    $arr[$subjectTag.'_'.$i.'_1_score'] = $arr[$subjectTag.'_'.$i.'_2_score'] = '';
                    $arr[$subjectTag.'_'.$i.'_1_grade'] = $arr[$subjectTag.'_'.$i.'_2_grade'] = '';
                }

                $arr['days_'.$i.'_1'] = $arr['days_'.$i.'_2'] = '';
                $arr['abs_1_'.$i.'_1'] = $arr['abs_1_'.$i.'_2'] = '';
                $arr['abs_2_'.$i.'_1'] = $arr['abs_2_'.$i.'_2'] = '';
                $arr['abs_3_'.$i.'_1'] = $arr['abs_3_'.$i.'_2'] = '';
                $arr['abs_6_'.$i.'_1'] = $arr['abs_6_'.$i.'_2'] = '';
                $arr['abs_total_'.$i.'_1'] = $arr['abs_total_'.$i.'_2'] = '';
            }

            // 學習領域評量
            $scores = $scoreSemester->getStudentScopeScore($row['sn']);
            $subjectTotalArr = array();
            $avgScoreArr = array();
            foreach ($scores as $yearSemester => $scoreData) {
                $subjectRateTotal = 0;
                $tempArr = explode('-',$yearSemester);
                $arr['grade_'.$tempArr[2].'_'.$tempArr[1]] = $tempArr[0];

                foreach ($subjectTagArray as $subjectTag=>$val) {
                    if (isset($scoreData['scope'][$val]['score'])) {
                        $arr[$subjectTag.'_'.$tempArr[2].'_'.$tempArr[1].'_score'] = $scoreData['scope'][$val]['score'];

                        if ($this->_finScoreRateMode == 'scopeAverage')  {//學分制加權
                            $subjectTotalArr[$subjectTag]['score'][] =
                            $scoreData['scope'][$val]['score'] * $scoreData['scope'][$val]['rate'];
                            $subjectTotalArr[$subjectTag]['total'][] = $scoreData['scope'][$val]['rate'];
                        }
                        else {
                            $subjectTotalArr[$subjectTag]['score'][] = $scoreData['scope'][$val]['score'];
                            $subjectTotalArr[$subjectTag]['total'][] = 1;
                        }
                    }
                    if (isset($scoreData['scope'][$val]['judge'])) {
                        $arr[$subjectTag.'_'.$tempArr[2].'_'.$tempArr[1].'_grade'] = $scoreData['scope'][$val]['judge'];
                        if ($this->_finScoreRateMode == 'scopeAverage' and $this->_displayFinScoreRate =='y') { //學分制加權
                            $arr[$subjectTag.'_'.$tempArr[2].'_'.$tempArr[1].'_grade'] .= '('. $scoreData['scope'][$val]['rate'].')';
                            $subjectRateTotal += $scoreData['scope'][$val]['rate'];
                        }
                    }
                }
                // 學期平均
                $arr[$tempArr[2].'_'.$tempArr[1].'_score'] = $scoreData['average']['score'];
                $arr[$tempArr[2].'_'.$tempArr[1].'_grade'] = $scoreData['average']['judge'];
                //                 if ($this->_finScoreRateMode == 'scopeAverage') //學分制加權
                //                  $arr[$tempArr[2].'_'.$tempArr[1].'_grade'] .= '('.$subjectRateTotal.')';

                // 總平均
                $avgScoreArr[] = $scoreData['average']['score'];
            }


            // 先取代為空值
            foreach ($subjectTotalArr as $id=>$val) {
                $arr[$id.'_avg_score'] = '';
                $arr[$id.'_avg_grade'] = '';
            }


            // 最後一學期再計算畢業成績
            if (count($scores) == $this->view->highYear *2) {
                $temp = end($scores);
                $judge = $temp['judge'];
                foreach ($subjectTotalArr as $id=>$val) {
                    $cc = count($val['score']);
                    if ($cc) {
                        $tempScore = round(array_sum($val['score']) /array_sum($val['total']), $this->_roundNum);
                        $arr[$id.'_avg_score'] = $tempScore;
                        $arr[$id.'_avg_grade'] =
                        Semester_Model_SemesterExamine::resolveJudgement($tempScore , $judge);
                        if ($this->_finScoreRateMode == 'scopeAverage' and $this->_displayFinScoreRate =='y') //學分制加權
                        $arr[$id.'_avg_grade'] .= '('.array_sum($val['total']).')';

                    }
                }

                if ($cc = count($avgScoreArr)) {
                    $arr['avg_score'] =  round(array_sum($avgScoreArr) /$cc, $this->_roundNum);
                    $arr['avg_grade']  =
                    Semester_Model_SemesterExamine::resolveJudgement($arr['avg_score'] , $judge);
                }

            }

            // 取代空標纖
            for($i =0 ; $i<6; $i++) {
                for($j=$this->view->loeYear; $j<=$this->view->highYear; $j++)
                $arr['nor_id'.$i.'_'.$j.'_1'] = $arr['nor_id'.$i.'_'.$j.'_2']  = '';
            }

            // 日常生活表現紀錄
            $studentComment = new Student_Model_StudentScoreComment();
            $commentData = $studentComment->getTable()->findBy('student_sn', $row['sn']);
            $commentArr = array();
            foreach($commentData as $val) {
                $commentArr[$val['year']][$val['semester']][$val['score_type']]['score'] = $val['score'];
                $commentArr[$val['year']][$val['semester']][$val['score_type']]['comment'] = $val['comment'];
            }


            // 出缺席記錄

            foreach ($row['Student_Model_StudentSemester'] as $val ) {
                $tempYS = $val['grade'].'_'.$val['semester'];
                $arr['abs_1_'.$tempYS] = $val['personal_leave'];
                $arr['abs_2_'.$tempYS] = $val['sick_leave'];
                $arr['abs_3_'.$tempYS] = $val['truancy'];
                $arr['abs_6_'.$tempYS] = $val['other_leave'];
                $arr['abs_total_'.$tempYS] =  $val['personal_leave']+ $val['sick_leave']+$val['truancy']+ $val['other_leave'];

                if (isset($presenceArr[$val['year']][$val['semester']][$val['grade']]))
                $arr['days_'.$tempYS] = $presenceArr[$val['year']][$val['semester']][$val['grade']] ;

                $arr['abs_1_sum'] +=  $arr['abs_1_'.$tempYS];
                $arr['abs_2_sum'] +=  $arr['abs_2_'.$tempYS];
                $arr['abs_3_sum'] +=  $arr['abs_3_'.$tempYS];
                $arr['abs_6_sum'] +=  $arr['abs_6_'.$tempYS];
                $arr['abs_total_sum'] +=  $arr['abs_total_'.$tempYS];
                if (isset($arr['days_'.$tempYS]))
                $arr['days_sum'] += $arr['days_'.$tempYS];
                for($i =0 ; $i<6; $i++) {
                    if (isset( $commentArr[$val['year']][$val['semester']][$i]['comment']))
                    $arr['nor_id'.$i.'_'.$tempYS] = $commentArr[$val['year']][$val['semester']][$i]['comment'];
                }

                // 導師
                $qRes = Doctrine_Query::create()
                ->from('Semester_Model_SemesterTeacher a')
                ->select('a.class_num, a.teacher_id, b.name AS name, b.sn AS sn')
                ->leftJoin('a.Teacher_Model_TeacherView  b')
                ->where('a.year=?',$val['year'])
                ->andwhere('a.semester=?',$val['semester'])
                ->andwhere('a.class_num=?', $val['grade'].'-'.$val['class_sn'])
                ->fetchOne();
                if ($qRes) {
                    $arr['teacher_'.$val['grade'].'_'.$val['semester']] = $qRes->name;//.'('.$qRes->class_num.')';
                }

            }
            //echo $row ['photo_name'].'--';exit;
            // 照片
            if ($row['photo_name'] != '') {
                $temp_sn = sprintf("%02X",$row['sn']);
                $len = (int) strlen($temp_sn) / 2;
                $path = '';
                for($i=0;$i<$len-1; $i++)
                $path .= substr($temp_sn,$i*2,2).'/';
                $file_path  = $this->_helper->getStorePath('photo/student/'.$path);
                $temp = explode('_',$row['photo_name']);
                $photo = 'tmb_'.$temp[0].'.'.$temp[1];
                if(is_file($file_path.$photo)) {
                    $photoName = 'Pictures/'.$temp[0].'.'.$temp[1];
                    $ooo->add_file(file_get_contents($file_path.$photo), $photoName);
                    $currentContentBody = str_replace($photoTag, $photoName, $contentBody);
                    $manifestStr .= '<manifest:file-entry manifest:media-type="image/jpeg" manifest:full-path="'.$photoName."\"/>\n";

                }
            }


            $replaceData  .= $ooo->change_temp($arr, $currentContentBody);
            if (count($res) > $page++)
            $replaceData .= $break;
        }
        $replaceData =$doc_head.$replaceData.$docFoot;
        $ooo->add_file($replaceData,'content.xml');

        // 照片處理
        $str = $ooo->getContent('META-INF/manifest.xml');
        // 排除檔案
        if ($manifestStr != '' ) {
            //echo $manifestStr; exit;
            $ooo->setSkipFile($photoTag);
            $tempArr = explode($splitStr, $str);
            $manifest = $tempArr[0].$manifestStr. $tempArr[1];
            $ooo->add_file($manifest,'META-INF/manifest.xml');
        }
        else
        $ooo->add_file($str,'META-INF/manifest.xml');



        $ooo->send_odt('report_'.$selYear.'_'.$selSemester.'_'.$selGrade.'_'.$selClassSn.'.odt');

    }


}


